package com.hmall.common.interceptor;

import com.hmall.common.utils.CollUtils;
import com.hmall.common.utils.UserContext;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Enumeration;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获得用户信息并存放到threadlocal中
//        1 获取用户信息
        String userInfo = request.getHeader("user-info");

//        2 判断用户信息是否为空
        if(userInfo == null || userInfo == ""){
            return true;
        }

//        3 不为空，则将信息储存
        UserContext.setUser(Long.valueOf(userInfo));

//        4 放行
        return true;
    }

    /*
    在用完后销毁
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserContext.removeUser();
    }
}
